from flask import Blueprint

from controllers import R
from mauth import HasPerm
from models.dict_item import DictItem
from services.dict_item_service import DictItemService
from validators import BasePageForm
from validators.id_validator import IdForm, IdsForm
from validators.dict_item_validator import DictItemForm

# 声明一个蓝图
dict_item = Blueprint("dict_item", __name__, url_prefix="/sys/dictItem")

# 声明一个字典项业务服务
dict_item_service = DictItemService(model=DictItem)


@dict_item.route("/detail", methods=["POST"])
@HasPerm(access="sys:dictItem:detail", name="通过id获取字典项信息")
def dict_item_detail():
    """
    通过id获取字典项信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = DictItem.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = dict_item_service.detail(form)
    if u is not None:
        return R.data(u.to_dict())
    else:
        return R.fail("该记录不存在")


@dict_item.route("/page", methods=["POST"])
@HasPerm(access="sys:dictItem:page", name="分页查询字典项列表")
def dict_item_page():
    """
    分页查询字典项列表
    :return:
    """
    form = BasePageForm()
    form.validate_for_api()
    return R.data(dict_item_service.page(form))


@dict_item.route("/save", methods=["POST"])
@HasPerm(access="sys:dictItem:save", name="添加字典项")
def dict_item_save():
    """
    添加字典项
    :return:
    """
    form = DictItemForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    dict_item_service.save(form)
    return R.success("添加字典项成功")


@dict_item.route("/update", methods=["POST"])
@HasPerm(access="sys:dictItem:update", name="修改字典项")
def dict_item_update():
    """
    修改字典项
    :return:
    """
    form = DictItemForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    dict_item_service.update(form)
    return R.success("修改字典项成功")


@dict_item.route("/remove", methods=["POST"])
@HasPerm(access="sys:dictItem:remove", name="删除字典项")
def dict_item_remove():
    """
    删除字典项
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    dict_item_service.remove(form)
    return R.success("删除字典项成功")
